package com.maysev.myjob_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maysev.myjob_backend.common.R;
import com.maysev.myjob_backend.entity.PerAuth;
import com.maysev.myjob_backend.entity.StuAuth;
import com.maysev.myjob_backend.entity.Student;
import com.maysev.myjob_backend.service.StuAuthService;
import com.maysev.myjob_backend.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * @author 五七
 * @create 2023-03-31 15:32
 * @description:
 */
@RestController
@RequestMapping("/stuAuth")
@Slf4j
@CrossOrigin("http://localhost:8082")
@Transactional
public class StuAuthController {


    @Autowired
    private StuAuthService stuAuthService;

    @Autowired
    private StudentService studentService;

    /**
     * 获取用户学生认证信息
     * @param userId
     * @return
     */
    @GetMapping
    private R<StuAuth> getStuAuthInfo(@RequestParam Long userId){
        //1. 根据用户id查询用户查询
        LambdaQueryWrapper<StuAuth> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StuAuth::getUserId,userId);
        StuAuth stu = stuAuthService.getOne(queryWrapper);
        //2. 未查到,则返回错误信息
        if(stu == null){
            //"0":表示未认证
            return R.error("未认证");
        }
        //3. 查询到,返回用户信息

        return R.success(stu);
    }

    /**
     * 添加或修改
     * @param stuAuth
     * @return
     */
    @PostMapping
    private R<String> submitStuAuthInfo(@RequestBody StuAuth stuAuth) {
         log.info(stuAuth.toString());
        //1.获取提交的认证信息
        LambdaQueryWrapper<StuAuth> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StuAuth::getUserId,stuAuth.getUserId());


        StuAuth one = stuAuthService.getOne(queryWrapper);
        //2.判断是添加还是修改
        if (one == null){
            //添加
            stuAuthService.save(stuAuth);


        }
        //修改
        stuAuthService.updateById(stuAuth);

        //将student表中的stu_status置为1

        LambdaQueryWrapper<Student> studentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        studentLambdaQueryWrapper.eq(Student::getId,stuAuth.getUserId());

        Student student = studentService.getOne(studentLambdaQueryWrapper);
        student.setStuStatus("1");

        studentService.updateById(student);


        return R.success("提交成功");
    }
}
